import Vue from 'vue'
import VueRouter from 'vue-router'

import HomeView from '../views/HomeView.vue'
import LoginPage from '../views/LoginPage.vue'
import Page404 from '../views/Page404.vue'

import AdminLayout from '../views/AdminLayout.vue'
import ArticleList from '../views/ArticleList.vue'
import ArticleAdd from '../views/ArticleAdd.vue'
import ArticleEdit from '../views/ArticleEdit.vue'
import ArtilceInfo from "../views/ArticleInfo2.vue"

import CateList from '../views/CateList.vue'
import CateAdd from '../views/CateAdd.vue'
import CateDetail  from '../views/CateDetail.vue'
import EditUser from '../views/EditUser.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect:"/login"  //默认跳转到 登录页面--新知01：路由重定向
  },
  {
    path: '/login',
    name: 'login',
    component:LoginPage
  },
  // 后台-后台的整体框架页面
  {
    path:'/admin',
    name:'admin',
    component:AdminLayout,
    redirect:'/admin/article/list', //后台的右边默认显示 文章列表

    //后台-所有页面，都作为admin的子路由
    //注意:子路由前面不要加 /,/表示首页
    children:[
      // 文章管理
      {
        // path: 'article', // /admin/article
        path: 'article/list', // /admin/article/list
        name: 'article_list',
        component: ArticleList
      },
      {
        path: 'article/add', // /admin/article/list
        name: 'article_add',
        component: ArticleAdd
      },
      {
        // path: 'article/edit', // /admin/article/edit
        // 动态路由 /admin/article/edit/62/1 ， /admin/article/edit/63/2
        path:'article/edit/:arc_id/:cate_id',
        name: 'article_edit',
        component: ArticleEdit
      },
      {
        path:'article/info/:arc_id/:class_id',
        name: 'article_info',
        component: ArtilceInfo
      },
      // 分类管理
      {
        path:"category/list",
        name:"category_list",
        component:CateList
      },
      {
        path:"category/add",
        name:"category_add",
        component:CateAdd
      },
      {
        path:"category/detail/:cid", // /admin/category/detail/1
        name:"category_add",
        component:CateDetail
      },
      {
        path:"setting/editUser",
        name:"setting_editUser",
        component:EditUser
      }
    ]
  },
  {
    path: '*', //任意没有匹配到的路由，进入此页面 --新知01：自定义404页面
    name:"page404",
    component:Page404
  }
]

const router = new VueRouter({
  routes
})

//路由全局守卫，来检查每个路由的权限
// http://localhost:8080/#/admin/article/list
// 获取用户是否登录
const isAuthenticated = localStorage.getItem("is_login"); // 0 未登录，1登录

router.beforeEach((to, from, next) => {
  console.log("这是检查站，每个人来了，都要安检",to,isAuthenticated)

  // 如果当前不是登录页面，并且没有登录，就跳转到登录页面
  if (to.name !== 'login' && !isAuthenticated){
    console.log(1)
    next({ name: 'login' }) //next 参数同this.$router.push() 数
  }
  else {
    console.log(2)
    next() //通过，进入下一个路由
  }
})

export default router
